// Copyright (C) joyinter
// All rights reserved.
// 
// Author : Jiang Li
// Date   : 2004-10-15

#include "stdafx.h"
#include "encpass.h"
#include <common/netmsg/aes.h>

static BYTE aesKey[] =
{
    0x73, 0x86, 0x71, 0x87, 0x98, 0xBB, 0xC4, 0xCD,
    0xA1, 0x79, 0xD2, 0x46, 0x35, 0x79, 0x5C, 0xD7,
    0xB6, 0xB4, 0x21, 0x66, 0x12, 0xCC, 0x8E, 0xF9,
    0xC1, 0xE2, 0x31, 0xD4, 0x59, 0xEF, 0x0F, 0xAA,
};

CJoyAes g_confEncrypter(aesKey, sizeof(aesKey));

BYTE HexToData(TCHAR c)
{
    if(c >= '0' && c <= '9')
    {
        return c-'0';
    }
    else if(c >= 'A' && c <= 'F')
    {
        return c-'A'+10;
    }
    else if(c >= 'a' && c <= 'f')
    {
        return c-'a'+10;
    }
    else
    {
        throw bad_cast();
    }
}
bool HexToData(LPVOID data, PCTSTR text, int len)
{
    try
    {
        PCTSTR end = text + len;
        BYTE* dat = (BYTE*)data;
        if(((len%2) != 0))
        {
            return false;
        }

        for(; text < end; text += 2, dat ++)
        {
            BYTE c0 = HexToData(text[0]);
            BYTE c1 = HexToData(text[1]);
            dat[0] = (c0<<4)+c1;
        }

        return true;
    }
    catch(...)
    {
        return false;
    }
}

__inline TCHAR DataToHex(int data)
{
    static TCHAR hexChar[] = 
    {
        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 
        'A', 'B', 'C', 'D', 'E', 'F', 
    };
    return hexChar[data];
}

void DataToHex(PTSTR text, LPCVOID data, int len)
{
    BYTE* dat = (BYTE*)data;
    BYTE* end = dat+len;
    for(; dat < end; dat ++, text += 2)
    {
        text[0] = DataToHex(dat[0] >> 4);
        text[1] = DataToHex(dat[0] & 0x0F);
    }
}

//##ModelId=44C4B5E6034C
enum PASS_CONST
{
	//##ModelId=44C4B5E6034E
    MAX_PASS    = 32,
	//##ModelId=44C4B5E6035B
    MAX_ENPASS  = MAX_PASS*2,
};

CString DecryptPass(PCTSTR pass)
{
    int len = (int)strlen(pass);

    if(len > MAX_ENPASS)
    {
        return CString();
    }

    TCHAR buf[MAX_PASS+1];
    memset(buf, 0, sizeof(buf));
    HexToData(buf, pass, len);

    g_confEncrypter.Decrypt(buf, buf, MAX_PASS);

    return CString(buf);
}

CString EncryptPass(PCTSTR pass)
{
    int len = (int)strlen(pass);

    BYTE enpass[MAX_PASS];
    memset(enpass, 0, sizeof(enpass));
    memcpy(enpass, pass, len);
    g_confEncrypter.Encrypt(enpass, enpass, MAX_PASS);

    TCHAR buf[MAX_ENPASS + 1];
    memset(buf, 0, sizeof(buf));
    DataToHex(buf, enpass, MAX_PASS);

    return CString(buf);
}
